package com.example.library.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.library.entity.Admin;
import com.example.library.mapper.AdminMapper;
import com.example.library.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sx
 * @since 2024-12-17
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private SecurityContext securityContext;

    @Override
    public Admin findByName(String name){
        return this.getOne(new QueryWrapper<Admin>().eq("name", name));
    }
    @Override
    public Admin login(String name, String password){
        Admin admin = adminMapper.selectByAdminName(name);
        if(admin != null && admin.getPassword().equals(password)){
            return admin;
        }
        return null;
    }

    @Override
    public Admin getCurrentAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
            return (Admin) authentication.getPrincipal(); // 根据你的用户对象类型返回具体用户
        }
        return null;
    }

    @Override
    public Admin getAdminByName(String name){
        return adminMapper.selectByAdminName(name);
    }
    @Override
    public Admin updateProfile(Admin admin) {
        Admin currentAdmin = getCurrentAdmin();
        if (currentAdmin != null) {
            // 更新当前登录管理员的信息
            currentAdmin.setName(admin.getName());
            currentAdmin.setEmail(admin.getEmail());
            adminMapper.updateByPrimaryKey(currentAdmin);
            return currentAdmin;
        }
        return null;
    }
}
